package com.sky.service.impl;

import com.sky.dto.ReportQueryDTO;
import com.sky.entity.MyXlsx;
import com.sky.entity.Orders;
import com.sky.exception.PermissionDeniedException;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import com.sun.deploy.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    ReportMapper reportMapper;

    @Override
    public OrderReportVO ordersStatistics(ReportQueryDTO reportQueryDTO) {
        return getOrdersStatistics(reportQueryDTO);
    }

    @Override
    public TurnoverReportVO turnoverStatistics(ReportQueryDTO reportQueryDTO) {
        return getTurnoverStatistics(reportQueryDTO);
    }

    @Override
    public UserReportVO userStatistics(ReportQueryDTO reportQueryDTO) {


        return getUserStatistics(reportQueryDTO);
    }

    @Override
    public SalesTop10ReportVO top10(ReportQueryDTO reportQueryDTO) {

        return getTop10(reportQueryDTO);
    }
    @Override
    public List<MyXlsx> export() {
        String begin=LocalDate.now().minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String end=LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        ReportQueryDTO reportQueryDTO=new ReportQueryDTO();
        reportQueryDTO.setBegin(begin);
        reportQueryDTO.setEnd(end);
        OrderReportVO orderReportVO=getOrdersStatistics(reportQueryDTO);
        TurnoverReportVO turnoverReportVO=getTurnoverStatistics(reportQueryDTO);
        UserReportVO userReportVO=getUserStatistics(reportQueryDTO);
        String orderCountList = orderReportVO.getOrderCountList();
        String validOrderCountList = orderReportVO.getValidOrderCountList();

        String[] split0 = turnoverReportVO.getDateList().split(",");
        List<String> dateL = Arrays.asList(split0);

        String[] split = orderCountList.split(",");
        List<String> orderCountL = Arrays.asList(split);
        split = validOrderCountList.split(",");
        List<String> validOrderCountL = Arrays.asList(split);


        String[] split1 = turnoverReportVO.getTurnoverList().split(",");
        List<String> turnoverL = Arrays.asList(split1);

        String[] split2 = userReportVO.getTotalUserList().split(",");
        List<String> totalUserL = Arrays.asList(split2);
        split2 = userReportVO.getNewUserList().split(",");
        List<String> newUserL = Arrays.asList(split2);

//        private List<String> ordersCount;
//        private List<String> validOrderCount;
//        private List<String> turnoverStatistics;
//        private List<String> totalUserList;
//        private List<String> newUserList;

        List<MyXlsx> myXlsxes=new ArrayList();
        for (int i = 0; i < orderCountL.size(); i++) {
            MyXlsx xlsx = MyXlsx.builder()
                    .date(dateL.get(i))
                    .ordersCount(orderCountL.get(i))
                    .newUserList(newUserL.get(i))
                    .totalUserList(totalUserL.get(i))
                    .turnoverStatistics(turnoverL.get(i))
                    .validOrderCount(validOrderCountL.get(i))
                    .build();
            myXlsxes.add(xlsx);
        }



        return myXlsxes;
    }



    private OrderReportVO getOrdersStatistics(ReportQueryDTO reportQueryDTO){

        LocalDate begin = LocalDate.parse(reportQueryDTO.getBegin());
        LocalDate end = LocalDate.parse(reportQueryDTO.getEnd());

        long daysDifference = ChronoUnit.DAYS.between(begin, end);

        if(daysDifference<0){
            throw new PermissionDeniedException("时间有误");
        }


        String localDate="";
        List<String> dateList=new ArrayList();
        List<String> counttList=new ArrayList<>();
        List<String> vcounttList=new ArrayList<>();
        Integer orderCount=0;
        Integer validOrderCount=0;


        dateList.add(reportQueryDTO.getBegin());
        for (int i=0;i<daysDifference;i++){
            begin=begin.plusDays(1);
            localDate = begin.toString();
            dateList.add(localDate);
        }
        for (String item : dateList) {
            Integer count = reportMapper.queryOrdersCount(item);
            Integer vcount = reportMapper.queryValidOrdersCount(item);
            counttList.add(count.toString());
            vcounttList.add(vcount.toString());
            orderCount+=count;
            validOrderCount+=vcount;
        }


        Double orderCompletionRate=validOrderCount/(orderCount+0.0);


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(counttList,","))
                .validOrderCountList(StringUtils.join(vcounttList,","))
                .totalOrderCount(orderCount)
                .validOrderCount(validOrderCount)
                .build();
    }
    public TurnoverReportVO getTurnoverStatistics(ReportQueryDTO reportQueryDTO) {
        LocalDate begin = LocalDate.parse(reportQueryDTO.getBegin());
        LocalDate end = LocalDate.parse(reportQueryDTO.getEnd());

        long daysDifference = ChronoUnit.DAYS.between(begin, end);

        if(daysDifference<0){
            throw new PermissionDeniedException("时间有误");
        }


        String localDate="";
        List<String> dateList=new ArrayList();
        List<String> amountList=new ArrayList<>();
        dateList.add(reportQueryDTO.getBegin());
        for (int i=0;i<daysDifference;i++){
            begin=begin.plusDays(1);
            localDate = begin.toString();
            dateList.add(localDate);
        }

        dateList.forEach((item)->{
            BigDecimal amount = reportMapper.queryComplateOrders(item);
            if(amount!=null){
                amountList.add(amount.toString());
            }else {
                amountList.add("0");
            }

        });

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(amountList,","))
                .build();
    }
    public UserReportVO getUserStatistics(ReportQueryDTO reportQueryDTO) {
        LocalDate begin = LocalDate.parse(reportQueryDTO.getBegin());
        LocalDate end = LocalDate.parse(reportQueryDTO.getEnd());

        long daysDifference = ChronoUnit.DAYS.between(begin, end);

        if(daysDifference<0){
            throw new PermissionDeniedException("时间有误");
        }


        String localDate="";
        List<String> dateList=new ArrayList();
        List<String> totalList=new ArrayList<>();
        List<String> newUserList=new ArrayList<>();
        dateList.add(reportQueryDTO.getBegin());
        for (int i=0;i<daysDifference;i++){
            begin=begin.plusDays(1);
            localDate = begin.toString();
            dateList.add(localDate);
        }
        dateList.forEach((item)->{
            Map total=reportMapper.queryTotal(item);
            Integer newUser=reportMapper.querynewUser(item);
            newUserList.add(newUser.toString());
            totalList.add(total.get("count").toString());
        });

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }
    public SalesTop10ReportVO getTop10(ReportQueryDTO reportQueryDTO) {
        reportQueryDTO.setEnd(reportQueryDTO.getEnd()+" 23:59:59");
        List<Map> top10=reportMapper.queryTop10(reportQueryDTO);
        List<String> nameList=new ArrayList<>();
        List<String>  numberList=new ArrayList<>();
        top10.forEach((item)->{
            nameList.add(item.get("name").toString());
            numberList.add(item.get("number").toString());
        });
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }
}
